package com.zoho.aimei.common;

import com.alibaba.fastjson.JSONObject;
import com.zoho.aimei.utils.HttpUtil;
import com.zoho.aimei.utils.SslUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.HashMap;
import java.util.Objects;

@Component
public class ZohoRecord {

    @Value("${zoho.refreshToken}")
    private String refreshToken;

    @Value("${zoho.clientId}")
    private String clientId;
    @Value("${zoho.clientSecret}")
    private String clientSecret;
    @Value("${zoho.redirectUri}")
    private String redirectUri;

    public String getAccessToken() {
        AccessTokenVo tokenVo = AccessTokenVo.getInstance();
        Long expireTime = tokenVo.getExpireTime();
        String token;
        // 按照过期时间判断，过期前10秒刷新token
        if (Objects.isNull(expireTime) || expireTime - System.currentTimeMillis() < 10000) {
            token = this.getAccessTokenByRefreshToken();
        } else {
            // 还未过期
            token = tokenVo.getAccessToken();
        }
        return token;
    }

    private String getAccessTokenByRefreshToken() {
        String url = "https://accounts.zoho.com/oauth/v2/token?grant_type=refresh_token&refresh_token=" + refreshToken + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + redirectUri;

        URL restURL;
        try {
            restURL = new URL(url);
            // PrintWriter out = null;
            //忽略HTTPS请求的SSL证书，必须在openConnection之前调用
            if ("https".equalsIgnoreCase(restURL.getProtocol())) {
                SslUtil.ignoreSsl();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = HttpUtil.postData(url, new HashMap<>());
        String token = jsonObject.getString("access_token");
        Long expiresIn = jsonObject.getLong("expires_in");
        AccessTokenVo.setInstance(System.currentTimeMillis() + (expiresIn * 1000), token);
        return token;
    }

}
